package token

import (
	"gin-base/common/models/admin"
	"github.com/gin-gonic/gin"
)

func SetAdmin() gin.HandlerFunc {
	return func(c *gin.Context) {
		var adminUser admin.Admin

		token := GetTokenFromHeader(c)

		if len(token) != 0 {
			adminUser = admin.LoginByAuthKey(token)
			c.Set("admin", &adminUser)
		}

		c.Next()
	}
}

func MustAdmin() gin.HandlerFunc {
	return func(c *gin.Context) {
		user := Admin(c)
		switch {
		case user == nil:
			c.String(401, "User not authorized")
			c.Abort()
		case user.ID == 0:
			c.String(401, "User not authorized")
			c.Abort()
		default:
			c.Next()
		}
	}
}

func Admin(c *gin.Context) *admin.Admin {
	v, ok := c.Get("admin")
	if !ok {
		return nil
	}
	u, ok := v.(*admin.Admin)
	if !ok {
		return nil
	}
	return u
}
